import { fetchCommunities } from "@/lib/actions/community.actions";
import SuggestCommunityCard from "../cards/SuggestCommunityCard";
import { fetchPosts } from "@/lib/actions/thread.actions";
import { currentUser } from "@clerk/nextjs";
import ThreadCard from "../cards/ThreadCard";
import { shuffleArray } from "@/lib/utils";

async function RightSidebar() {
  // 社区组织
  const result = await fetchCommunities({
    searchString: "",
    pageNumber: 1,
    pageSize: 25,
  });
  const communityResult_ = shuffleArray(result.communities).slice(0, 2);
  result.communities = communityResult_;

  // 获取帖子
  const postResult = await fetchPosts(1, 4);
  const postResult_ = shuffleArray(postResult.posts).slice(0, 2);
  postResult.posts = postResult_;

  const user = await currentUser();
  if (!user) return null;

  return (
    <section className="custom-scrollbar rightsidebar">
      <div className="flex flex-1 flex-col justify-start">
        <h3 className="text-heading4-medium text-black dark:text-light-1">
          Suggested Communities
        </h3>
        <section className="mt-9 flex flex-wrap gap-4 max-w-sm">
          {result.communities.length === 0 ? (
            <p className="no-result">No Result</p>
          ) : (
            <>
              {result.communities.map((community) => (
                <SuggestCommunityCard
                  key={community.id}
                  id={community.id}
                  name={community.name}
                  username={community.username}
                  imgUrl={community.image}
                  bio={community.bio}
                  members={community.members}
                />
              ))}
            </>
          )}
        </section>
      </div>

      <div className="flex flex-1 flex-col justify-start">
        <h3 className="text-heading4-medium text-black dark:text-light-1">
          Similar Minds
        </h3>
        <section className="mt-9 flex flex-wrap gap-4 max-w-sm">
          {postResult.posts.length === 0 ? (
            <p className="no-result">No threads found</p>
          ) : (
            <>
              {postResult.posts.map((post) => (
                <ThreadCard
                  key={post._id}
                  id={post._id}
                  currentUserId={user.id}
                  parentId={post.parentId}
                  content={post.text}
                  author={post.author}
                  community={post.community}
                  createdAt={post.createdAt}
                  comments={post.children}
                  isSimilar={true} // 首页推荐
                />
              ))}
            </>
          )}
        </section>
      </div>
    </section>
  );
}

export default RightSidebar;
